package com.anti.modular.sys.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.anti.commom.constant.CommonConstant;
import com.anti.commom.core.exception.BusinessException;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.modular.sys.app.entity.SysApp;
import com.anti.modular.sys.app.param.SysAppParam;
import com.anti.modular.sys.app.service.SysAppService;
import com.anti.modular.sys.user.enums.SysUserAdminTypeEnum;
import com.anti.modular.sys.user.entity.SysUser;
import com.anti.modular.sys.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2021-2-26
 */
@Service
public class SysAppServiceImpl implements SysAppService {
    @Resource
    DBUtils dbUtils;
    @Resource
    SysUserService sysUserService;
    @Override
    public List<Dict> getLoginApps(Long userId) {
        List<Dict> userAppDictList = CollectionUtil.newArrayList();

        SysUser sysUser = sysUserService.getById(userId);
        Integer adminType = sysUser.getAdminType();
        String sql="";
        List<SysApp> query;
        //如果不是超级管理员则有自己的菜单对应的应用编码
        if (!SysUserAdminTypeEnum.SUPER_ADMIN.getCode().equals(adminType)) {
            //获取用户菜单对应的应用编码集合
            sql="SELECT a.id,a.name,a.code FROM sys_role r,sys_role_menu rm,sys_menu m,sys_app a " +
                    " WHERE r.STATUS = 0 and r.id=rm.role_id and rm.menu_id=m.id  and a.code=m.application and a.status=0" +
                    " AND r.id IN (SELECT role_id FROM sys_user_role WHERE user_id =? ) GROUP BY a.id,a.name,a.code";
            query= dbUtils.query(sql, SysApp.class, userId);
        }else {
            sql="SELECT a.id,a.name,a.code FROM sys_app a where a.status=0";
            query= dbUtils.query(sql, SysApp.class);
        }

        //当应用编码不为空时，则限制查询范围
        if (ObjectUtil.isEmpty(query)) {
            //没查到应用编码则直接返回
            return userAppDictList;
        }
        //遍历
        query.forEach(sysApp -> {
            Dict dict = Dict.create();
            dict.put(CommonConstant.CODE, sysApp.getCode());
            dict.put(CommonConstant.NAME, sysApp.getName());
            //如果有默认激活的
            if ("Y".equals(sysApp.getActive())) {
                dict.put("active", true);
                //将其放在第一个
                userAppDictList.add(0, dict);
            } else {
                dict.put("active", false);
                userAppDictList.add(dict);
            }
        });
        return userAppDictList;
    }


    @Override
    public void add(SysAppParam sysAppParam) {
        //校验参数，检查是否存在相同的名称和编码，以及默认激活的系统的数量是否合理
        checkParam(sysAppParam, false);
        String sql="INSERT INTO sys_app (name, code, active, status, create_time, create_user) VALUES (?,?, 'N', 0, ?, ?)";
        Long loginUserId = LoginContextHolder.me().getSysLoginUserId();
        dbUtils.execSql(sql,sysAppParam.getName(),sysAppParam.getCode(),new Date(),loginUserId);
    }

    @Override
    public void delete(SysAppParam sysAppParam) {
        dbUtils.execSql("update sys_app set status=2 where id =?",sysAppParam.getId());
    }

    @Override
    public void edit(SysAppParam sysAppParam) {
        checkParam(sysAppParam, true);
        String sql="update sys_app set name=?, code=?, update_time=?, update_user=? where id=?";
        Long loginUserId = LoginContextHolder.me().getSysLoginUserId();
        dbUtils.execSql(sql,sysAppParam.getName(),sysAppParam.getCode(),new Date(),loginUserId,sysAppParam.getId());
    }

    @Override
    public void updateAsDefault(SysAppParam sysAppParam) {
        dbUtils.execSql("update sys_app set active='N' where active ='Y'");
        dbUtils.execSql("update sys_app set active='Y' where id =?",sysAppParam.getId());
    }


    @Override
    public List<SysApp> list(SysAppParam sysAppParam) {
        String sql="select * from sys_app where status=0 ";
        return dbUtils.query(sql,SysApp.class);
    }

    private void checkParam(SysAppParam sysAppParam, boolean b) {
        Long id = sysAppParam.getId();
        String name = sysAppParam.getName();
        String code = sysAppParam.getCode();
        if (b){
            // 查询名称,编码有无重复
            String checkAppName="select count(*) from sys_app where (name=? or code =?) and id<>? and status=0 ";
            Integer integer = dbUtils.getFirst(checkAppName, Integer.class, name, code,id);
            if (integer >= 1){
                throw new BusinessException(0,"应用名称或编码已存在！");
            }
        }else {
            // 查询名称,编码有无重复
            String checkAppName="select count(*) from sys_app where (name=? or code =?) and status=0 ";
            Integer integer = dbUtils.getFirst(checkAppName, Integer.class, name, code);
            if (integer >= 1){
                throw new BusinessException(0,"应用名称或编码已存在！");
            }
        }
    }

    @Override
    public PageResult page(PageParam pageParam, SysAppParam sysAppParam) {
        StringBuilder sb=new StringBuilder("SELECT * FROM sys_app WHERE STATUS=0 ");
        if (ObjectUtil.isNotNull(sysAppParam)) {
            //根据名称模糊查询
            if (ObjectUtil.isNotEmpty(sysAppParam.getName())) {
                sb.append(" and name like '%"+sysAppParam.getName()+"%'");
            }
            //根据编码模糊查询
            if (ObjectUtil.isNotEmpty(sysAppParam.getCode())) {
                sb.append(" and code like '%"+sysAppParam.getCode()+"%'");
            }
        }
        PageResult pageResult = dbUtils.query(pageParam, sb.toString());
        return pageResult;
    }
}
